Assign contents of structure into another structure with “fieldname-paths” of variable depth (dynamic fieldnames)
2 views (last 30 days)
Show older comments
I have a structure in MATLAB, CurrStructSubset, of which the content/all fieldnames (not the structure itself!) should be added to another structure, OverViewStruct, but, the path of fieldnames within this structure where the contents of CurrStructSubset should be saved to, is variable. It can be OverViewStruct.toplevel at some run, and at another run it might be OverViewStruct.toplevel.secondlevel.thirdlevel.bottomlevel ... . An example below:
This is my structure I want to append another structure to:
OverViewStruct =
bankcontact: [1x1 struct]
food: [1x1 struct]
sociaal: [1x1 struct]
transport: [1x1 struct]
vastekosten: [1x1 struct]
This is the structure I want to append:
CurrStructSubset = getfield(OverViewStruct,fields{:});
Supsequently a particular number of fields are added to CurrStructSubset, in this case, only 'cadeau'.
CurrStructSubset =
TotalSpent: 20
LogicalSaveMatchesVec: [59x1 logical]
PercSpent: 0.029814
NormalizedSpending: 57.542
cadeau: [1x1 struct]
with fields{:} = sociaal
I don't know the names of the fieldnames of CurrStructSubset beforehand, as they are not fixed, and neither are the number of fieldnames. How can I elegantly replace the current content of e.g. OverViewStruct.sociaal with the contents of CurrStructSubset without making CurrStructSubset a fieldname itself? So I want OverViewStruct.sociaal.cadeau and not OverViewStruct.sociaal.CurrStructSubset.cadeau. Take in mind that 'field' can contain any number of fields each time the script is called ... .
setfield(OverViewStruct,fields{:},CurrStructSubset); doesn't seem to do anything
0 Comments
Answers (1)
Walter Roberson
on 13 Nov 2013
When I worked on something similar, I realized that what I was looking for was a "structure merge" routine. Recursively copy fields from structure2 into structure1, creating new branches as needed, overwriting items that already had values, leaving intact anything that was not mentioned in the second structure.
I have my source for the resulting routine, but I am not permitted to release it in its current form (would have to be rewritten for copyright reasons). I think, though, it is safe to say that stripped over the error checking, the easiest way to implement it is recursively.
See Also
Categories
Find more on Structures in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!