changeset 6167:d9e9c436abb0

[project @ 2006-11-15 15:22:46 by jwe]
author jwe
date Wed, 15 Nov 2006 15:22:46 +0000
parents 17f25cd588b2
children a3cd9e6fcd9c
files scripts/miscellaneous/substruct.m
diffstat 1 files changed, 86 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
new file mode 100644
--- /dev/null
+++ b/scripts/miscellaneous/substruct.m
@@ -0,0 +1,86 @@
+## Copyright (C) 2006  John W. Eaton
+##
+## This file is part of Octave.
+##
+## Octave is free software; you can redistribute it and/or modify it
+## under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 2, or (at your option)
+## any later version.
+##
+## Octave is distributed in the hope that it will be useful, but
+## WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+## General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with Octave; see the file COPYING.  If not, write to the Free
+## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+## 02110-1301, USA.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {} setfield (@var{type}, @var{subs}, @dots{})
+## Create a subscript structure for use with @code{subsref} or
+## @code{subsasgn}.
+##
+## @example
+## @group
+## @end group
+## @end example
+## @seealso{subsref, subsasgn}
+## @end deftypefn
+
+## Author:  jwe
+
+function retval = substruct (varargin)
+
+  nargs = nargin;
+
+  if (nargs > 1 && mod (nargs, 2) == 0)
+    narg_pairs = nargs / 2;
+    typ = cell (narg_pairs, 1);
+    sub = cell (narg_pairs, 1);
+    k = 1;
+    for i = 1:2:nargs
+      t = varargin{i};
+      dot = false;
+      switch (t)
+	case { "()", "{}" }
+	case "."
+	  dot = true;
+	otherwise
+	  error ("substruct: expecting type to be one of \"()\", \"{}\", or \".\"");
+      endswitch
+      s = varargin{i+1};
+      if (dot)
+	if (! ischar (s))
+	  error ("substruct: for type == %s, subs must be a character string", t);
+	endif
+      elseif (! (iscell (s) || (ischar (s) && strcmp (s, ":"))))
+	error ("substruct: for type == %s, subs must be a cell array or \":\"",
+	       t);
+      endif
+      typ{k} = t;
+      sub{k} = s;
+      k++;
+    endfor
+    retval = struct ("type", typ, "subs", sub);
+  else
+    print_usage ();
+  endif
+
+endfunction
+
+%!test
+%! x(1,1).type = "()";
+%! x(2,1).type = "{}";
+%! x(3,1).type = ".";
+%! x(1,1).subs = {1,2,3};
+%! x(2,1).subs = ":";
+%! x(3,1).subs = "foo";
+%! y = substruct ("()", {1,2,3}, "{}", ":", ".", "foo");
+%! assert(x,y);
+%!error assert(substruct);
+%!error assert(substruct (1, 2, 3));
+%!error assert(substruct ("x", 1));
+%!error assert(substruct ("()", [1,2,3]));
+%!error assert(substruct (".", {1,2,3}));