0

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]
1
  • 1
    I think the only way to do this is to iterate over all fields and all elements of the struct array. Commented Oct 7, 2020 at 19:32

2 Answers 2

1

You can just do:

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

foo = 

  struct with fields:

    b: [1 2]
Sign up to request clarification or add additional context in comments.

2 Comments

Yes but I would like to have a function. Since .b isnt the only struct field. E.g. fun(foo1,foo2,foo3,...) etc... Further I can have an array... foo(i).b, in that sense
@WG- All that information (function, several fields, arrays) should have been initially included in the question
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.