Jeon
Jeon

Reputation: 4076

Concatenating two or more struct-type variables in MATLAB

Assuming types of all variables are struct and have same fields with concatenatable size (dimensions). For example:

a.x = 1; a.y = 2;
b.x = 10; b.y = 20;

With the ordinary concatenation:

c = [a; b];

returns

c(1).x = 1; c(1).y = 2;
c(2).x = 10; c(2).y = 20;

What I want is:

c.x(1) = 1; c.y(1) = 2;
c.x(2) = 10; c.y(2) = 20;

It can be done by:

c.x = [a.x; b.x];
c.y = [a.y; b.y;];

However, if the variables have lots of fields,

a.x1 = 1;
a.x2 = 2;
% Lots of fields here
a.x100 = 100;

It's a waste of time to write such a code. Is there any good way to do this?

Upvotes: 5

Views: 128

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

If all contents are numbers, or row vectors of the same size, it can be done without loops:

f = fieldnames(a);   
t = [f mat2cell(cell2mat([struct2cell(a) struct2cell(b)]), ones(1,numel(f)))].';
c = struct(t{:});

The idea here is to generate a cell array of strings (t) such that when expanded to a comma-separated list (t{:}) it will generate the input arguments to struct necessary to build c.

Example:

a.x = [1 1]; a.y = [2 2]; a.z = [3 3];
b.x = [10 100]; b.y = [20 200]; b.z = [30 300];

gives

c = 

    x: [1 1 10 100]
    y: [2 2 20 200]
    z: [3 3 30 300]

Upvotes: 1

user664303
user664303

Reputation: 2063

This function does what you want, but has no error checking:

function C = cat_struct(A, B)
C = struct();
for f = fieldnames(A)'
   C.(f{1}) = [A.(f{1}); B.(f{1})];
end

You would use it like this in your code above:

c = cat_struct(a, b);

Upvotes: 2

Related Questions