Search code examples
matlabstructure

MATLAB: How do I combine a structure array with same size field values into one structure


I have a structure array where each field of the same name is the same size. I want to combine each field over the array into one field. For example:

A(1).x = [1 2 3];
A(1).y = [4 5 6];
A(2).x = [7 8 9];
A(2).y = [10 11 12];

I want the new structure to be

B.x = [1 2 3;
       7 8 9];
B.y = [4 5 6;
       10 11 12];

These could also be a cell of structures if that makes things easier.


Solution

  • A.x produces a comma-separated list of values. You can use this comma-separated list in a function call, in which case each value is treated as a separate argument. This is very useful, as you can pass it into a call to cat to concatenate the values:

    B.x = cat(1, A.x);
    

    You'd have to do this same operation for each of the fields. To automate this you could iterate over fieldnames(A):

    for name = fieldnames(A).'
       B.(name{1}) = cat(1, A.(name{1}));
    end