7017
|
1 ## Copyright (C) 2006, 2007 John W. Eaton |
6167
|
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. |
6167
|
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/>. |
6167
|
18 |
|
19 ## -*- texinfo -*- |
6744
|
20 ## @deftypefn {Function File} {} substruct (@var{type}, @var{subs}, @dots{}) |
6167
|
21 ## Create a subscript structure for use with @code{subsref} or |
|
22 ## @code{subsasgn}. |
|
23 ## @seealso{subsref, subsasgn} |
|
24 ## @end deftypefn |
|
25 |
|
26 ## Author: jwe |
|
27 |
|
28 function retval = substruct (varargin) |
|
29 |
|
30 nargs = nargin; |
|
31 |
|
32 if (nargs > 1 && mod (nargs, 2) == 0) |
|
33 narg_pairs = nargs / 2; |
|
34 typ = cell (narg_pairs, 1); |
|
35 sub = cell (narg_pairs, 1); |
|
36 k = 1; |
|
37 for i = 1:2:nargs |
|
38 t = varargin{i}; |
|
39 dot = false; |
|
40 switch (t) |
|
41 case { "()", "{}" } |
|
42 case "." |
|
43 dot = true; |
|
44 otherwise |
|
45 error ("substruct: expecting type to be one of \"()\", \"{}\", or \".\""); |
|
46 endswitch |
|
47 s = varargin{i+1}; |
|
48 if (dot) |
|
49 if (! ischar (s)) |
|
50 error ("substruct: for type == %s, subs must be a character string", t); |
|
51 endif |
|
52 elseif (! (iscell (s) || (ischar (s) && strcmp (s, ":")))) |
|
53 error ("substruct: for type == %s, subs must be a cell array or \":\"", |
|
54 t); |
|
55 endif |
|
56 typ{k} = t; |
|
57 sub{k} = s; |
|
58 k++; |
|
59 endfor |
|
60 retval = struct ("type", typ, "subs", sub); |
|
61 else |
|
62 print_usage (); |
|
63 endif |
|
64 |
|
65 endfunction |
|
66 |
|
67 %!test |
|
68 %! x(1,1).type = "()"; |
|
69 %! x(2,1).type = "{}"; |
|
70 %! x(3,1).type = "."; |
|
71 %! x(1,1).subs = {1,2,3}; |
|
72 %! x(2,1).subs = ":"; |
|
73 %! x(3,1).subs = "foo"; |
|
74 %! y = substruct ("()", {1,2,3}, "{}", ":", ".", "foo"); |
|
75 %! assert(x,y); |
|
76 %!error assert(substruct); |
|
77 %!error assert(substruct (1, 2, 3)); |
|
78 %!error assert(substruct ("x", 1)); |
|
79 %!error assert(substruct ("()", [1,2,3])); |
|
80 %!error assert(substruct (".", {1,2,3})); |