5820
|
1 ## Copyright (C) 2000 Etienne Grossmann |
|
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 |
|
7 ## the Free Software Foundation; either version 2, or (at your option) |
|
8 ## any later version. |
|
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 |
|
16 ## along with Octave; see the file COPYING. If not, write to the Free |
|
17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
|
18 ## 02110-1301, USA. |
|
19 |
|
20 ## -*- texinfo -*- |
6157
|
21 ## @deftypefn {Function File} {[@var{k1},..., @var{v1}] =} setfield (@var{s}, @var{k1}, @var{v1}, @dots{}) |
5881
|
22 ## Set field members in a structure. |
5820
|
23 ## |
|
24 ## @example |
|
25 ## @group |
|
26 ## oo(1,1).f0= 1; |
|
27 ## oo = setfield(oo,@{1,2@},'fd',@{3@},'b', 6); |
|
28 ## oo(1,2).fd(3).b == 6 |
|
29 ## @result{} ans = 1 |
|
30 ## @end group |
|
31 ## @end example |
|
32 ## |
|
33 ## Note that this function could be written |
|
34 ## |
|
35 ## @example |
|
36 ## i1= @{1,2@}; i2= 'fd'; i3= @{3@}; i4= 'b'; |
|
37 ## oo( i1@{:@} ).( i2 )( i3@{:@} ).( i4 ) == 6; |
|
38 ## @end example |
|
39 ## @seealso{getfield, rmfield, isfield, isstruct, fieldnames, struct} |
|
40 ## @end deftypefn |
|
41 |
|
42 ## Author: Etienne Grossmann <etienne@cs.uky.edu> |
|
43 |
|
44 function obj = setfield (obj, varargin) |
|
45 field = "obj"; |
|
46 for i = 1:nargin-2 |
|
47 v = varargin{i}; |
|
48 if (iscell (v)) |
|
49 sep = "("; |
|
50 for j = 1:length (v) |
|
51 field = sprintf ("%s%s%s", field, sep, num2str (v{j})); |
|
52 sep = ","; |
|
53 endfor |
|
54 field = sprintf ("%s)", field); |
|
55 else |
|
56 field = sprintf ("%s.%s", field, v); |
|
57 endif |
|
58 endfor |
|
59 val = varargin{nargin-1}; |
|
60 eval (sprintf ("%s=val;", field)); |
|
61 endfunction |
|
62 |
|
63 %!test |
|
64 %! x.a = "hello"; |
|
65 %! x = setfield(x,"b","world"); |
|
66 %! y = struct('a','hello','b','world'); |
|
67 %! assert(x,y); |
|
68 %!test |
|
69 %! oo(1,1).f0= 1; |
|
70 %! oo = setfield(oo,{1,2},'fd',{3},'b', 6); |
|
71 %! assert (oo(1,2).fd(3).b, 6) |