comparison scripts/miscellaneous/setfield.m @ 9849:87fd803c583b

rewrite getfield and setfield
author Jaroslav Hajek <highegg@gmail.com>
date Fri, 20 Nov 2009 14:46:13 +0100
parents 1bf0ce0930be
children 9d1a14e12431
comparison
equal deleted inserted replaced
9848:6867676107f3 9849:87fd803c583b
1 ## Copyright (C) 2000, 2006, 2007, 2009 Etienne Grossmann 1 ## Copyright (C) 2000, 2006, 2007, 2009 Etienne Grossmann
2 ## Copyright (C) 2009 VZLU Prague
2 ## 3 ##
3 ## This file is part of Octave. 4 ## This file is part of Octave.
4 ## 5 ##
5 ## Octave is free software; you can redistribute it and/or modify it 6 ## 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 ## under the terms of the GNU General Public License as published by
41 ## @end deftypefn 42 ## @end deftypefn
42 43
43 ## Author: Etienne Grossmann <etienne@cs.uky.edu> 44 ## Author: Etienne Grossmann <etienne@cs.uky.edu>
44 45
45 function obj = setfield (obj, varargin) 46 function obj = setfield (obj, varargin)
46 field = "obj"; 47 if (nargin < 3)
47 for i = 1:nargin-2 48 print_usage ();
48 v = varargin{i}; 49 endif
49 if (iscell (v)) 50 subs = varargin(1:end-1);
50 sep = "("; 51 rhs = varargin{end};
51 for j = 1:length (v) 52 flds = cellfun (@ischar, subs);
52 field = sprintf ("%s%s%s", field, sep, num2str (v{j})); 53 idxs = cellfun (@iscell, subs);
53 sep = ","; 54 if (all (flds | idxs))
54 endfor 55 typs = merge (flds, {"."}, {"()"});
55 field = sprintf ("%s)", field); 56 obj = subsasgn (obj, struct ("type", typs, "subs", subs), rhs);
56 else 57 else
57 field = sprintf ("%s.%s", field, v); 58 error ("setfield: invalid index");
58 endif 59 endif
59 endfor
60 val = varargin{nargin-1};
61 eval (sprintf ("%s=val;", field));
62 endfunction 60 endfunction
63 61
64 %!test 62 %!test
65 %! x.a = "hello"; 63 %! x.a = "hello";
66 %! x = setfield(x,"b","world"); 64 %! x = setfield(x,"b","world");