Match Fields of two structs (without a loop if possible)
Show older comments
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
James Tursa
on 25 Jul 2017
Edited: James Tursa
on 25 Jul 2017
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?
Dominik Bleidorn
on 25 Jul 2017
James Tursa
on 25 Jul 2017
Edited: James Tursa
on 25 Jul 2017
So merge the stuff from B that is not currently in A into A? Both new fields and new elements? What about subfields?
Dominik Bleidorn
on 25 Jul 2017
Answers (2)
Walter Roberson
on 25 Jul 2017
0 votes
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
James Tursa
on 25 Jul 2017
Edited: James Tursa
on 25 Jul 2017
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
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!