# HG changeset patch # User jwe # Date 1163604166 0 # Node ID d9e9c436abb0214cc195a0a1ff748fe695ace9d9 # Parent 17f25cd588b21b5f9aca6e8040a395f603a5d04d [project @ 2006-11-15 15:22:46 by jwe] diff -r 17f25cd588b2 -r d9e9c436abb0 scripts/miscellaneous/substruct.m --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/scripts/miscellaneous/substruct.m Wed Nov 15 15:22:46 2006 +0000 @@ -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}));