1########################################################################
2##
3## Copyright (C) 2019-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 {} {} mustBeNonnegative (@var{x})
28##
29## Require that input @var{x} is not negative.
30##
31## Raise an error if any element of the input @var{x} is negative, as
32## determined by @code{@var{x} >= 0}.
33##
34## @seealso{mustBeNonzero, mustBePositive}
35## @end deftypefn
36
37function mustBeNonnegative (x)
38
39  if (nargin != 1)
40    print_usage ();
41  endif
42
43  tf = (x(:) >= 0);
44  if (! all (tf))
45    label = inputname (1);
46    if (isempty (label))
47      label = "input";
48    endif
49    bad_idx = find (! tf);
50    try
51      bad_val = x(bad_idx);
52      errmsg = sprintf ("%s must be non-negative; found %d elements that were not: values %s", ...
53                        label, numel (bad_idx), mat2str (bad_val));
54    catch
55      errmsg = sprintf ("%s must be non-negative; found %d elements that were not: indexes %s", ...
56                        label, numel (bad_idx), mat2str (bad_idx));
57    end_try_catch
58    error (errmsg);
59  endif
60
61endfunction
62
63
64%!test
65%! mustBeNonnegative (0);
66%! mustBeNonnegative (1);
67%! mustBeNonnegative (123.456);
68%! mustBeNonnegative (Inf);
69%! mustBeNonnegative (0:10);
70%! mustBeNonnegative (eps);
71
72%!error <Invalid call> mustBeNonnegative ()
73%!error <input must be non-negative> mustBeNonnegative (-1)
74%!error <found 1 elements> mustBeNonnegative ([0 1 2 3 -4])
75%!error <input must be non-negative> mustBeNonnegative (-Inf)
76%!error <must be non-negative> mustBeNonnegative (NaN)
77