1 ## Copyright (C) 2004-2012 Paul Kienzle
3 ## This file is part of Octave.
5 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
10 ## Octave is distributed in the hope that it will be useful, but
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ## General Public License for more details.
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING. If not, see
17 ## <http://www.gnu.org/licenses/>.
19 ## Original version by Paul Kienzle distributed as free software in the
23 ## @deftypefn {Function File} {} sprand (@var{m}, @var{n}, @var{d})
24 ## @deftypefnx {Function File} {} sprand (@var{s})
25 ## Generate a random sparse matrix. The size of the matrix will be
26 ## @var{m} by @var{n}, with a density of values given by @var{d}.
27 ## @var{d} should be between 0 and 1. Values will be uniformly
28 ## distributed between 0 and 1.
30 ## If called with a single matrix argument, a random sparse matrix is
31 ## generated wherever the matrix @var{S} is non-zero.
32 ## @seealso{sprandn, sprandsym}
35 ## Author: Paul Kienzle <pkienzle@users.sf.net>
39 ## Piotr Krzyzanowski <przykry2004@users.sf.net>
40 ## 2004-09-27 use Paul's hint to allow larger random matrices
41 ## at the price of sometimes lower density than desired
43 ## 2004-10-20 Texinfo help and copyright message
45 function S = sprand (m, n, d)
48 S = __sprand_impl__ (m, @rand);
50 S = __sprand_impl__ (m, n, d, "sprand", @rand);
58 %! s = sprand (4, 10, 0.1);
59 %! assert (size (s), [4, 10]);
60 %! assert (nnz (s) / numel (s), 0.1);
62 %% Test 1-input calling form
64 %! s = sprand (sparse ([1 2 3], [3 2 3], [2 2 2]));
65 %! [i, j, v] = find (s);
66 %! assert (sort (i), [1 2 3]');
67 %! assert (sort (j), [2 3 3]');
68 %! assert (all (v > 0 & v < 1));
70 %% Test input validation
73 %!error sprand (1, 2, 3, 4)
74 %!error sprand (ones(3), 3, 0.5)
75 %!error sprand (3.5, 3, 0.5)
76 %!error sprand (0, 3, 0.5)
77 %!error sprand (3, ones(3), 0.5)
78 %!error sprand (3, 3.5, 0.5)
79 %!error sprand (3, 0, 0.5)
80 %!error sprand (3, 3, -1)
81 %!error sprand (3, 3, 2)