How to combine two or multiple structs with different fields?

136 Ansichten (letzte 30 Tage)
YZ
YZ am 7 Dez. 2016
Kommentiert: Rob Campbell am 13 Apr. 2021
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.

Antworten (2)

Walter Roberson
Walter Roberson am 7 Dez. 2016

David Barry
David Barry am 7 Dez. 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 Kommentare
Walter Roberson
Walter Roberson am 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 am 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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by