필터 지우기
필터 지우기

How to combine two or multiple structs with different fields?

조회 수: 149 (최근 30일)
YZ
YZ 2016년 12월 7일
댓글: Rob Campbell 2021년 4월 13일
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에서 Data Type Conversion에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by