1 ## Copyright (C) 2001 Laurent Mazet
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
17 ## @deftypefn {Function File} {@var{b} = } randint (@var{n})
18 ## @deftypefnx {Function File} {@var{b} = } randint (@var{n},@var{m})
19 ## @deftypefnx {Function File} {@var{b} = } randint (@var{n},@var{m},@var{range})
20 ## @deftypefnx {Function File} {@var{b} = } randint (@var{n},@var{m},@var{range},@var{seed})
22 ## Generate a matrix of random binary numbers. The size of the matrix is
23 ## @var{n} rows by @var{m} columns. By default @var{m} is equal to @var{n}.
25 ## The range in which the integers are generated will is determined by
26 ## the variable @var{range}. If @var{range} is an integer, the value will
27 ## lie in the range [0,@var{range}-1], or [@var{range}+1,0] if @var{range}
28 ## is negative. If @var{range} contains two elements the intgers will lie
29 ## within these two elements, inclusive. By default @var{range} is
30 ## assumed to be [0:1].
32 ## The variable @var{seed} allows the random number generator to be seeded
33 ## with a fixed value. The initial seed will be restored when returning.
39 function b = randint (n, m, range, seed)
53 usage ("b = randint (n, [m, [range, [seed]]])");
57 if (length (range) == 1)
63 elseif ( prod (size (range)) != 2)
64 error ("randint: range must be a 2 element vector");
70 old_seed = rand ("seed");
74 b = range (1) - 1 + ceil (rand (n, m) * (range (2) - range (1) + 1));
76 ## Get back to the old
78 rand ("seed", old_seed);
83 %!shared n, m, seed, a1, a2, a3, a4, a5, a6
84 %! n = 10; m = 32; seed = 1; a1 = randint(n); a2 = randint(n,n);
85 %! a3 = randint(n,n,m); a4 = randint(n,n,[-m,m]);
86 %! a5 = randint(n,n,m, seed); a6 = randint(n,n,m, seed);
89 %!error randint (n,n,n,n,n);
90 %!assert (size(a1) == [n, n] && size(a2) == [n, n]);
91 %!assert (max ([a1(:); a2(:)]) <= 1 && min([a1(:); a2(:)]) >= 0);
92 %!assert (size(a3) == [n, n] && size(a4) == [n, n]);
93 %!assert (max (a3(:)) < m && min(a3(:)) >= 0);
94 %!assert (max (a4(:)) <= m && min(a4(:)) >= -m);
95 %!assert (a5(:) == a6(:));
98 %! a = randint(10,10,-32);
99 %! assert (max(a(:)) <= 0 && min(a(:)) > -32);