Extracting everything from a structure
50 ビュー (過去 30 日間)
古いコメントを表示
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
0 件のコメント
採用された回答
その他の回答 (3 件)
Jan
2011 年 6 月 3 日
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
2011 年 6 月 3 日
Don't do that: http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F
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 件のコメント
Walter Roberson
2011 年 6 月 3 日
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.
Sean de Wolski
2011 年 6 月 3 日
doc struct2cell
?
2 件のコメント
Sean de Wolski
2011 年 6 月 3 日
The values and their indeces should be all you need, per the FAQ link.
参考
カテゴリ
Help Center および File Exchange で Structures についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!