Indexing over all values in nested struct

≯℡__Kan透↙ 提交于 2019-12-09 03:49:26

问题


I have a nested struct which contains values and is defined as:

mystruct.level1.a = 1;
mystruct.level1.b = 2;
mystruct.level2.a = 8;
mystruct.level2.b = 9;

I want to perform operations on the elements in level1 and level2. What I want to do is access the values in level1 and level2, put them in a vector, without referencing the nested field names.

E.g. I'd like to do something like:

level1_vector = [mystruct.level1]

Which I would like to output:

level1_vector = [1 2]

How can I do that?


回答1:


Use the combination of two functions below:

cell2mat(struct2cell(mystruct.level1))




回答2:


There's a structfun to do just that. It will return another struct, with the same names. So for your case:

con_struct = structfun (@(x) [x.a x.b], mystruct, "UniformOutput", false);

Now, con_struct will have the same fields as mystruct, but instead of a struct, each of them is an array with the values you wanted. You can feed each of arrays again to whatever function you want

structfun (@foo, con_struct)


来源:https://stackoverflow.com/questions/16448885/indexing-over-all-values-in-nested-struct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!