What are some efficient ways to combine two structures in MATLAB?

前端 未结 5 1747
我在风中等你
我在风中等你 2020-11-29 11:01

I want to combine two structures with differing fields names.

For example, starting with:

A.field1 = 1;
A.field2 = \'a\';

B.field3 = 2;
B.field4 = \         


        
5条回答
  •  遥遥无期
    2020-11-29 11:50

    Without collisions, you can do

    M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)'];
    C=struct(M{:});
    

    And this is reasonably efficient. However, struct errors on duplicate fieldnames, and pre-checking for them using unique kills performance to the point that a loop is better. But here's what it would look like:

    M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)'];
    
    [tmp, rows] = unique(M(1,:), 'last');
    M=M(:, rows);
    
    C=struct(M{:});
    

    You might be able to make a hybrid solution by assuming no conflicts and using a try/catch around the call to struct to gracefully degrade to the conflict handling case.

提交回复
热议问题