7017
|
1 ## Copyright (C) 2000, 2006, 2007 Etienne Grossmann |
5820
|
2 ## |
|
3 ## This file is part of Octave. |
|
4 ## |
|
5 ## Octave is free software; you can redistribute it and/or modify it |
|
6 ## under the terms of the GNU General Public License as published by |
7016
|
7 ## the Free Software Foundation; either version 3 of the License, or (at |
|
8 ## your option) any later version. |
5820
|
9 ## |
|
10 ## Octave is distributed in the hope that it will be useful, but |
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ## General Public License for more details. |
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
7016
|
16 ## along with Octave; see the file COPYING. If not, see |
|
17 ## <http://www.gnu.org/licenses/>. |
5820
|
18 |
|
19 ## -*- texinfo -*- |
6547
|
20 ## @deftypefn {Function File} {[@var{k1}, @dots{}, @var{v1}] =} setfield (@var{s}, @var{k1}, @var{v1}, @dots{}) |
5881
|
21 ## Set field members in a structure. |
5820
|
22 ## |
|
23 ## @example |
|
24 ## @group |
8507
|
25 ## oo(1,1).f0 = 1; |
|
26 ## oo = setfield (oo, @{1,2@}, "fd", @{3@}, "b", 6); |
5820
|
27 ## oo(1,2).fd(3).b == 6 |
|
28 ## @result{} ans = 1 |
|
29 ## @end group |
|
30 ## @end example |
|
31 ## |
|
32 ## Note that this function could be written |
|
33 ## |
|
34 ## @example |
8507
|
35 ## i1 = @{1,2@}; i2 = "fd"; i3 = @{3@}; i4 = "b"; |
|
36 ## oo(i1@{:@}).(i2)(i3@{:@}).(i4) == 6; |
5820
|
37 ## @end example |
|
38 ## @seealso{getfield, rmfield, isfield, isstruct, fieldnames, struct} |
|
39 ## @end deftypefn |
|
40 |
|
41 ## Author: Etienne Grossmann <etienne@cs.uky.edu> |
|
42 |
|
43 function obj = setfield (obj, varargin) |
|
44 field = "obj"; |
|
45 for i = 1:nargin-2 |
|
46 v = varargin{i}; |
|
47 if (iscell (v)) |
|
48 sep = "("; |
|
49 for j = 1:length (v) |
|
50 field = sprintf ("%s%s%s", field, sep, num2str (v{j})); |
|
51 sep = ","; |
|
52 endfor |
|
53 field = sprintf ("%s)", field); |
|
54 else |
|
55 field = sprintf ("%s.%s", field, v); |
|
56 endif |
|
57 endfor |
|
58 val = varargin{nargin-1}; |
|
59 eval (sprintf ("%s=val;", field)); |
|
60 endfunction |
|
61 |
|
62 %!test |
|
63 %! x.a = "hello"; |
|
64 %! x = setfield(x,"b","world"); |
8507
|
65 %! y = struct("a","hello","b","world"); |
5820
|
66 %! assert(x,y); |
|
67 %!test |
|
68 %! oo(1,1).f0= 1; |
8507
|
69 %! oo = setfield(oo,{1,2},"fd",{3},"b", 6); |
5820
|
70 %! assert (oo(1,2).fd(3).b, 6) |