Match Fields of two structs (without a loop if possible)

Hello!
I have two different structs. Struct A has , say, 3 different Fields: Field1, Field2,Field3. Struct B has 5 different Fields: Field1, Field2,Field3, Field4, Field5. Field1-3 are the same in my case.
Is it possible to match the Fields of A to the Fields of B, but without a loop?
My current solution is to gather all unique fieldnames in both structs in a cellarray and then loop through them, adding a 0 in a not used column and then removing that one afterwards.
I'm not really happy about that solution and would like to know if there is a better way to handle this.
Edit: To clarify it, my desired output is the original struct A with all the Fields of A and B.
struct_A = struct('Field1', 1, 'Field2', 2, 'Field3',3);
struct_B = struct('Field1', 10, 'Field2', 20, 'Field3',30,'Field4' ,40, 'Field5',50);
struct_AGoal = struct('Field1', 1, 'Field2', 2, 'Field3',3,'Field4' ,0, 'Field5',0);
Greetings D.
.

4 Comments

What is your desired output? New struct A and B that contain only the fields that are common to both? Or just a list of the common field names?
My desired output is to have struct A, but with all the Fields of A and B.
So merge the stuff from B that is not currently in A into A? Both new fields and new elements? What about subfields?
Currently I need just the Fields.
Lets say struct B, the bigger one, contains all possible properties of fruits in different forms 'isGreen' , 'IsRed', 'isBend' , 'Weight'. Struct A then discribes the properties of an red Apple, but only the non-Zero values. So it is only 'IsRed': 1 , 'Weight' : 30
What I want is to make a full set of Data, including things like 'IsGreen' : 0.

Sign in to comment.

Answers (2)

As an outline as I am not at my desk,
struct2cell B, index cell, at not (ismember Bfieldnames, Afieldnames). cat that onto struct2cell A. cell2struct the result.
If you need to append the matching fields then a bit more work needs to be done
I don't think loops is such a bad way for this application. There will be some incremental data copying going on, but the only data being copied are mxArray pointers. So unless the struct has an extremely large number of fields or elements the loop will not be much of a burden. E.g., assuming these are scalar structs:
Af = fieldnames(A);
Bf = fieldnames(B);
x = ismember(Bf,Af);
Bf = Bf(~x);
for k=1:numel(Bf)
A.(Bf{k}) = 0;
end
If B could be a non-scalar struct, then another outer loop would need to be added for that.

Categories

Asked:

on 25 Jul 2017

Edited:

on 25 Jul 2017

Community Treasure Hunt

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

Start Hunting!