1 ## Copyright (C) 2000-2012 Etienne Grossmann
2 ## Copyright (C) 2009 VZLU Prague
4 ## This file is part of Octave.
6 ## Octave is free software; you can redistribute it and/or modify it
7 ## under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 3 of the License, or (at
9 ## your option) any later version.
11 ## Octave is distributed in the hope that it will be useful, but
12 ## WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ## General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with Octave; see the file COPYING. If not, see
18 ## <http://www.gnu.org/licenses/>.
21 ## @deftypefn {Function File} {[@var{k1}, @dots{}, @var{v1}] =} setfield (@var{s}, @var{k1}, @var{v1}, @dots{})
22 ## Set a field member in a (nested) structure array. For example:
27 ## oo = setfield (oo, @{1,2@}, "fd", @{3@}, "b", 6);
28 ## oo(1,2).fd(3).b == 6
33 ## Note that the same result as in the above example could be achieved by:
37 ## i1 = @{1,2@}; i2 = "fd"; i3 = @{3@}; i4 = "b";
38 ## oo(i1@{:@}).(i2)(i3@{:@}).(i4) == 6
42 ## @seealso{getfield, rmfield, isfield, isstruct, fieldnames, struct}
45 ## Author: Etienne Grossmann <etienne@cs.uky.edu>
47 function obj = setfield (obj, varargin)
51 subs = varargin(1:end-1);
53 flds = cellfun ("isclass", subs, "char");
54 idxs = cellfun ("isclass", subs, "cell");
55 if (all (flds | idxs))
56 typs = merge (flds, {"."}, {"()"});
57 obj = subsasgn (obj, struct ("type", typs, "subs", subs), rhs);
59 error ("setfield: invalid index");
65 %! x = setfield(x,"b","world");
66 %! y = struct("a","hello","b","world");
70 %! oo = setfield(oo,{1,2},"fd",{3},"b", 6);
71 %! assert (oo(1,2).fd(3).b, 6)