]> Creatis software - CreaPhase.git/blob - octave_packages/m/sparse/sprand.m
update packages
[CreaPhase.git] / octave_packages / m / sparse / sprand.m
1 ## Copyright (C) 2004-2012 Paul Kienzle
2 ##
3 ## This file is part of Octave.
4 ##
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.
9 ##
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.
14 ##
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/>.
18 ##
19 ## Original version by Paul Kienzle distributed as free software in the
20 ## public domain.
21
22 ## -*- texinfo -*-
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.
29 ##
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}
33 ## @end deftypefn
34
35 ## Author: Paul Kienzle <pkienzle@users.sf.net>
36 ##
37 ## Changelog:
38 ##
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
42 ## David Bateman
43 ##      2004-10-20      Texinfo help and copyright message
44
45 function S = sprand (m, n, d)
46
47   if (nargin == 1 )
48     S = __sprand_impl__ (m, @rand);
49   elseif ( nargin == 3)
50     S = __sprand_impl__ (m, n, d, "sprand", @rand);
51   else
52     print_usage ();
53   endif
54
55 endfunction
56
57 %!test
58 %! s = sprand (4, 10, 0.1);
59 %! assert (size (s), [4, 10]);
60 %! assert (nnz (s) / numel (s), 0.1);
61
62 %% Test 1-input calling form
63 %!test
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));
69
70 %% Test input validation
71 %!error sprand ()
72 %!error sprand (1, 2)
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)
82