Clear Filters
Clear Filters

How to combine two or multiple structs with different fields?

149 views (last 30 days)
A is 1x1 struct, with field a = 'good'. A.a = 'good'
B is 1x1 struct, with field a = 'good', and b = 'USA'. B.a = 'good'; B.b = 'USA';
How to construct C, which is 2x1 struct, so that C(1)=A and C(2)=B, and also A now has the field B = '' (empty). I can't use the way here (https://www.mathworks.com/help/matlab/matlab_prog/concatenate-structures.html) because A and B have different fields.
I need to find an automatic way to combine because I have to read A, B, C,..Z, and I don't know how many fields each of them have. But they have similar fields, but some fields are only in some structs. Thank you.

Answers (2)

Walter Roberson
Walter Roberson on 7 Dec 2016

David Barry
David Barry on 7 Dec 2016
It's a bit of an odd thing to want to do. If you really want to stick with the structs then I think you will need to loop over all of them, find the unique set of fieldnames and then add the missing fields to the appropriate structs. Not particularly nice or efficient. How about using a table instead? This will sort out the missing fields for you as you dynamically add data.
t = table;
t.FirstName{1, 1} = 'Bob';
t.FirstName{2, 1} = 'John';
t.LastName{2, 1} = 'Smith';
  3 Comments
Walter Roberson
Walter Roberson on 19 Sep 2019
I wrote a structure merge function a number of years ago. In context, I was creating a batch of "updates" to a structure that might or might not have the fields needing to be set. In context it was cleaner and more efficient to create a struct of the updates and call my routine to merge the two -- so copy the field from the first structure if it did not exist in the second, and otherwise copy it from the second. In context I did not need to worry about appending data within a field (which is also a valid thing to want to do.)
There are uses for such things.
Rob Campbell
Rob Campbell on 13 Apr 2021
Agreed, there are definitely very good use cases for this. e.g. I just made a structure containing software settings. The first few fields are common. The remaining ones depend on the task the user is doing. e.g. The user chooses to work in regime A or B and gets back a single structure with fields tailored for that job. The code that generates has no redundancy since I have one function that generates the common settings then two more for regimes A and B. More can be added in future and they work as independent modules.

Sign in to comment.

Categories

Find more on Data Type Conversion 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!