WG-
WG-

Reputation: 1070

Matlab merge two structs to one single array

I have to identical structs. How can I combine the two values of the struct to an array efficiently?

foo1.b = 1
foo2.b = 2

How can I merge these two variables to... foo1 and foo2 to...

foo.b = [1 2]

Upvotes: 0

Views: 126

Answers (2)

MichaelTr7
MichaelTr7

Reputation: 4767

Here's a pretty rudimentary try at a function that combines structures. The only condition is that the structs need to all have an equal number of fields/members. It was a bit of a piecing/glueing code together but...

The input signature varargin (variable input arguments) allows a variable number of inputs into a function. The nargin variable indicates the number of input arguments. By using a bit of trial and error the right types can be created. The function fieldnames() allows for the retrieval of the field names within the structures inputted.

%Structure 1%
foo1.b = 1;
foo1.a = 2;
foo1.c = 5;

%Structure 2%
foo2.b = 3;
foo2.a = 1;
foo2.c = 4;

%Structure 3%
foo3.b = 5;
foo3.a = 2;
foo3.c = 7;

%Function call%
[foo] = Combine_Structures(foo1,foo2,foo3);
foo.a
foo.b
foo.c


%Function%
function [foo] =  Combine_Structures(varargin)

Number_Of_Fields = numel(fieldnames(varargin{1}));
Field_Names = fieldnames(varargin{1});


Number_Of_Inputs = nargin;
Variable_Input_Arguments = varargin;
Argument_Array = (1:Number_Of_Inputs);
    
Structures = Variable_Input_Arguments;


for Field_Index = 1: Number_Of_Fields
Field = string(Field_Names(Field_Index));

Combined_Array = [Structures{1:Number_Of_Inputs}];
Combined_Array = [Combined_Array(1:Number_Of_Inputs).(Field)];


foo.(Field) = Combined_Array;

end

end

Using MATLAB version: R2019b

Upvotes: 0

user2317421
user2317421

Reputation:

You can just do:

>> foo.b = [foo1.b foo2.b]

foo = 

  struct with fields:

    b: [1 2]

Upvotes: 1

Related Questions