]> Creatis software - CreaPhase.git/blob - octave_packages/m/miscellaneous/getfield.m
update packages
[CreaPhase.git] / octave_packages / m / miscellaneous / getfield.m
1 ## Copyright (C) 2000-2012 Etienne Grossmann
2 ## Copyright (C) 2009 VZLU Prague
3 ##
4 ## This file is part of Octave.
5 ##
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.
10 ##
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.
15 ##
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/>.
19
20 ## -*- texinfo -*-
21 ## @deftypefn {Function File} {[@var{v1}, @dots{}] =} getfield (@var{s}, @var{key}, @dots{})
22 ## Extract a field from a structure (or a nested structure).  For example:
23 ##
24 ## @example
25 ## @group
26 ## ss(1,2).fd(3).b = 5;
27 ## getfield (ss, @{1,2@}, "fd", @{3@}, "b")
28 ##    @result{} 5
29 ## @end group
30 ## @end example
31 ##
32 ## Note that the function call in the previous example is equivalent to
33 ## the expression
34 ##
35 ## @example
36 ## @group
37 ## i1 = @{1,2@}; i2 = "fd"; i3 = @{3@}; i4= "b";
38 ## ss(i1@{:@}).(i2)(i3@{:@}).(i4)
39 ##    @result{} 5
40 ##
41 ## @end group
42 ## @end example
43 ## @seealso{setfield, rmfield, isfield, isstruct, fieldnames, struct}
44 ## @end deftypefn
45
46 ## Author: Etienne Grossmann <etienne@cs.uky.edu>
47
48 function obj = getfield (s, varargin)
49   if (nargin < 2)
50     print_usage ();
51   endif
52   subs = varargin;
53   flds = cellfun ("isclass", subs, "char");
54   idxs = cellfun ("isclass", subs, "cell");
55   if (all (flds | idxs))
56     typs = merge (flds, {"."}, {"()"});
57     obj = subsref (s, struct ("type", typs, "subs", subs));
58   else
59     error ("getfield: invalid index");
60   endif
61 endfunction
62
63 %!test
64 %! x.a = "hello";
65 %! assert(getfield(x,"a"),"hello");
66 %!test
67 %! ss(1,2).fd(3).b = 5;
68 %! assert(getfield(ss,{1,2},'fd',{3},'b'),5)