Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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...)</p> <p>I use a function I wrote a few years back called <code>setdefaults.m</code>, which combines one structure with the values of another structure, where one takes precedence over the other in case of conflict.</p> <pre><code>% 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 </code></pre> <p>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 (<code>setdefaults2.m</code>):</p> <pre><code>% 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 </code></pre> <p>and some samples to test it:</p> <pre><code>&gt;&gt; S1 = struct('a',1,'b',2,'c',3); &gt;&gt; S2 = struct('b',4,'c',5,'d',6); &gt;&gt; setdefaults2(S1,S2) ans = b: 2 c: 3 d: 6 a: 1 &gt;&gt; setdefaults2(S2,S1) ans = a: 1 b: 4 c: 5 d: 6 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload