问题
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