1########################################################################
2##
3## Copyright (C) 2008-2021 The Octave Project Developers
4##
5## See the file COPYRIGHT.md in the top-level directory of this
6## distribution or <https://octave.org/copyright/>.
7##
8## This file is part of Octave.
9##
10## Octave is free software: you can redistribute it and/or modify it
11## under the terms of the GNU General Public License as published by
12## the Free Software Foundation, either version 3 of the License, or
13## (at your option) any later version.
14##
15## Octave is distributed in the hope that it will be useful, but
16## WITHOUT ANY WARRANTY; without even the implied warranty of
17## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18## GNU General Public License for more details.
19##
20## You should have received a copy of the GNU General Public License
21## along with Octave; see the file COPYING.  If not, see
22## <https://www.gnu.org/licenses/>.
23##
24########################################################################
25
26## -*- texinfo -*-
27## @deftypefn  {} {} optimget (@var{options}, @var{parname})
28## @deftypefnx {} {} optimget (@var{options}, @var{parname}, @var{default})
29## Return the specific option @var{parname} from the optimization options
30## structure @var{options} created by @code{optimset}.
31##
32## If @var{parname} is not defined then return @var{default} if supplied,
33## otherwise return an empty matrix.
34## @seealso{optimset}
35## @end deftypefn
36
37function retval = optimget (options, parname, default)
38
39  if (nargin < 2 || nargin > 4 || ! isstruct (options) || ! ischar (parname))
40    print_usage ();
41  endif
42
43  ## Expand partial-length names into full names
44  opts = __all_opts__ ();
45  idx = strncmpi (opts, parname, length (parname));
46  nmatch = sum (idx);
47
48  if (nmatch == 1)
49    parname = opts{idx};
50  elseif (nmatch == 0)
51    warning ("optimget: unrecognized option: %s", parname);
52  else
53    fmt = sprintf ("optimget: ambiguous option: %%s (%s%%s)",
54                   repmat ("%s, ", 1, nmatch-1));
55    warning (fmt, parname, opts{idx});
56  endif
57
58  if (isfield (options, parname) && ! isempty (options.(parname)))
59    retval = options.(parname);
60  elseif (nargin > 2)
61    retval = default;
62  else
63    retval = [];
64  endif
65
66endfunction
67
68
69%!shared opts
70%! opts = optimset ("tolx", 0.1, "maxit", 100);
71%!assert (optimget (opts, "TolX"), 0.1)
72%!assert (optimget (opts, "maxit"), 100)
73%!assert (optimget (opts, "MaxITer"), 100)
74%!assert (optimget (opts, "TolFun"), [])
75%!assert (optimget (opts, "TolFun", 1e-3), 1e-3)
76
77## Test input validation
78%!error optimget ()
79%!error optimget (1)
80%!error optimget (1,2,3,4,5)
81%!error optimget (1, "name")
82%!error optimget (struct (), 2)
83%!warning <unrecognized option: foobar> (optimget (opts, "foobar"));
84%!warning <ambiguous option: Max> (optimget (opts, "Max"));
85