How to combine two or multiple structs with different fields?

136 次查看(过去 30 天)
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.

回答(2 个)

Walter Roberson
Walter Roberson 2016-12-7

David Barry
David Barry 2016-12-7
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 个评论
Walter Roberson
Walter Roberson 2019-9-19
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 2021-4-13
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by