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

前端 未结 5 1745
我在风中等你
我在风中等你 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:34

    I don't think you can handle conflicts well w/o a loop, nor do I think you'd need to avoid one. (although I suppose efficiency could be an issue w/ many many fields...)

    I use a function I wrote a few years back called setdefaults.m, which combines one structure with the values of another structure, where one takes precedence over the other in case of conflict.

    % SETDEFAULTS sets the default structure values 
    %    SOUT = SETDEFAULTS(S, SDEF) reproduces in S 
    %    all the structure fields, and their values,  that exist in 
    %    SDEF that do not exist in S. 
    %    SOUT = SETDEFAULTS(S, SDEF, OVERRIDE) does
    %    the same function as above, but if OVERRIDE is 1,
    %    it copies all fields of SDEF to SOUT.
    
    function sout = setdefaults(s,sdef,override)
    if (not(exist('override','var')))
        override = 0;
    end
    
    sout = s;
    for f = fieldnames(sdef)'
        cf = char(f);
        if (override | not(isfield(sout,cf)))
            sout = setfield(sout,cf,getfield(sdef,cf));
        end
    end
    

    Now that I think about it, I'm pretty sure that the "override" input is unnecessary (you can just switch the order of the inputs) though I'm not 100% sure of that... so here's a simpler rewrite (setdefaults2.m):

    % SETDEFAULTS2 sets the default structure values 
    %    SOUT = SETDEFAULTS(S, SDEF) reproduces in S 
    %    all the structure fields, and their values,  that exist in 
    %    SDEF that do not exist in S. 
    
    function sout = setdefaults2(s,sdef)
    sout = sdef;
    for f = fieldnames(s)'
        sout = setfield(sout,f{1},getfield(s,f{1}));
    end
    

    and some samples to test it:

    >> S1 = struct('a',1,'b',2,'c',3);
    >> S2 = struct('b',4,'c',5,'d',6);
    >> setdefaults2(S1,S2)
    
    ans = 
    
        b: 2
        c: 3
        d: 6
        a: 1
    
    >> setdefaults2(S2,S1)
    
    ans = 
    
        a: 1
        b: 4
        c: 5
        d: 6
    

提交回复
热议问题