2

Is there any simple way to combine the following two structures, without using for loop or CELLFUN?

struct1 = 

    a: {43x1 cell}

struct2 = 

    b: [43x1 double]
    c: {43x1 cell}

I would like to have the combined structure like this:

struct3 = 

    a: {43x1 cell}
    b: [43x1 double]
    c: {43x1 cell}
Barpa
  • 275
  • 1
  • 3
  • 13
  • 1
    possible duplicate of [update struct via another struct in Matlab](http://stackoverflow.com/questions/15245167/update-struct-via-another-struct-in-matlab) and [What are some efficient ways to combine two structures in MATLAB?](http://stackoverflow.com/questions/38645/what-are-some-efficient-ways-to-combine-two-structures-in-matlab). – Eitan T Mar 17 '13 at 08:57
  • Thanks, I found the answer in [update struct via another struct in Matlab](http://stackoverflow.com/questions/15245167/update-struct-via-another-struct-in-matlab) – Barpa Mar 17 '13 at 10:21

2 Answers2

8

I got what I want by using the suggestion in update struct via another struct in Matlab, as follows:

names = [fieldnames(struct1); fieldnames(struct2)];
struct3 = cell2struct([struct2cell(struct1); struct2cell(struct2)], names, 1);
Community
  • 1
  • 1
Barpa
  • 275
  • 1
  • 3
  • 13
0

Consider this article and associated MATLAB Exchange script from Mathworks:

Subject:

How can I concatenate or merge two structures? Problem Description:

I would like to merge two structures into a new structure containing all the fields of the two original structures. How can I do this in MATLAB?

Solution:

There is no direct ability in MATLAB that can be used to concatenate structures.

The attached file mergeStructs.m shows a number of methods that can be used to merge structures in MATLAB.

There are also online submissions on the MATLAB Central User Community that you can use. One such submission is :

http://www.mathworks.com/matlabcentral/fileexchange/7842

Note that MathWorks does not guarantee or warrant the use or content of these submissions. Any questions, issues, or complaints should be directed to the contributing author.

Steve
  • 3,957
  • 2
  • 26
  • 50