Assign contents of structure into another structure with “fieldname-paths” of variable depth (dynamic fieldnames)
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Walter Roberson
2013-11-13
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!