3

I am trying to merge two structs with identical fields. I tried several ways, such as this and this. But it either turns out sideways or doesn't work at all.

My two (simplified) structs are

a(1).name = 'x';
a(1).data = 1;
a(2).name = 'y';
a(2).data = 2;

and

b(1).name = 'x';
b(1).data = 3;
b(2).name = 'y';
b(2).data = 4;

The desired output is identical to what this would produce:

c(1).name = 'x';
c(1).data = 1;
c(2).name = 'y';
c(2).data = 2;
c(3).name = 'x';
c(3).data = 3;
c(4).name = 'y';
c(4).data = 4;

What is an easy way to do this? In my real struct, there are more than two fields with over a thousand values.

Community
  • 1
  • 1
Arthur Tarasov
  • 3,517
  • 9
  • 45
  • 57

2 Answers2

1

The following does that.

%-------------------------------------------------------
a(1).name = 'x';
a(1).data = 1;
a(2).name = 'y';
a(2).data = 2;
b(1).name = 'x';
b(1).data = 3;
b(2).name = 'y';
b(2).data = 4;

c = struct('name',{a(:).name,b(:).name},'data',{a(:).data,b(:).data});
%-------------------------------------------------------
>> c(1)
ans =
    name: 'x'
    data: 1
>> c(2)
ans =
    name: 'y'
    data: 2
>> c(3)
ans =
    name: 'x'
    data: 3
>> c(4)
ans =
    name: 'y'
    data: 4
Developer
  • 8,258
  • 8
  • 49
  • 58
1

This was answered tersely in a comment by Matthias W., so I'll elaborate here...

When structures have identical fields, you can treat them just as any other object when concatenating them. The solution for the above example would be:

c = [a b];

Since a and b in this case are 1-by-2 structure arrays, this horizontally concatenates them into a larger 1-by-4 structure array. If the sizes/dimensions of a and b weren't known, we could do this:

c = [a(:).' b(:).'];

This uses the colon operator to reshape them into column arrays, then transposes them into row arrays before concatenating them.

More complicated cases...

  • Merge fields across structures: This question deals with the case when you want to combine multiple structures (with the same fields) into a single structure (not a structure array). In this case, each individual field is being concatenated across a number of structures.

  • Merge different structures into one: This question deals with the case where you have multiple structures with different fields and you want to merge them into one single structure with all the fields from each individual structure. The caveat that has to be considered here is how to handle collisions: if the same field appears in multiple structures, which field value appears in the final merged structure?

Community
  • 1
  • 1
gnovice
  • 125,304
  • 15
  • 256
  • 359