[37] | 1 | function ab = setfields(a, b, newfield_flag)
|
---|
| 2 | %SETFIELDS Set multiple fields of a structure.
|
---|
| 3 | % SETFIELDS(A,B), where A and B are structures, returns a copy of A where
|
---|
| 4 | % the fields named in B have the values specified in B. If B contains fields
|
---|
| 5 | % not in A, signals an error.
|
---|
| 6 | % SETFIELDS(A,B,'create') allows B to contain new fields, which are added to A.
|
---|
| 7 | % SETFIELDS(A,B,'ignore') ignores new fields in B.
|
---|
| 8 | %
|
---|
| 9 | % Examples:
|
---|
| 10 | % a.a = 1
|
---|
| 11 | % b.b = 2
|
---|
| 12 | % setfields(a,b) % error
|
---|
| 13 | % setfields(a,b,'create') % ans = struct('a',1,'b',2)
|
---|
| 14 | % setfields(a,b,'ignore') % ans = struct('a',1)
|
---|
| 15 |
|
---|
| 16 | % Written by Tom Minka,
|
---|
| 17 | % based on mergestruct.m by Martin Szummer and Yuan Qi.
|
---|
| 18 | % (The arguments are flipped with respect to mergestruct.)
|
---|
| 19 | % (c) Microsoft Corporation. All rights reserved.
|
---|
| 20 |
|
---|
| 21 | if nargin < 3
|
---|
| 22 | newfield_flag = '';
|
---|
| 23 | end
|
---|
| 24 | ab = a;
|
---|
| 25 | if isempty(b)
|
---|
| 26 | return
|
---|
| 27 | end
|
---|
| 28 | bfields = fieldnames(b);
|
---|
| 29 | switch newfield_flag
|
---|
| 30 | case 'create'
|
---|
| 31 | % do nothing
|
---|
| 32 | case 'ignore'
|
---|
| 33 | existing = ismember(bfields, fieldnames(a));
|
---|
| 34 | bfields = bfields(find(existing));
|
---|
| 35 | case ''
|
---|
| 36 | existing = ismember(bfields, fieldnames(a));
|
---|
| 37 | if any(~existing)
|
---|
| 38 | a
|
---|
| 39 | b
|
---|
| 40 | error('attempt to set non-existent fields');
|
---|
| 41 | end
|
---|
| 42 | otherwise
|
---|
| 43 | error('unrecognized option');
|
---|
| 44 | end
|
---|
| 45 |
|
---|
| 46 | for i = 1:length(bfields)
|
---|
| 47 | ab = setfield(ab, bfields{i}, getfield(b, bfields{i}));
|
---|
| 48 | end
|
---|