7017
|
1 ## Copyright (C) 2004, 2005, 2006, 2007 Paul Kienzle |
5164
|
2 ## |
7016
|
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. |
5164
|
21 |
|
22 ## -*- texinfo -*- |
5610
|
23 ## @deftypefn {Function File} {} sprandn (@var{m}, @var{n}, @var{d}) |
|
24 ## @deftypefnx {Function File} {} sprandn (@var{s}) |
5164
|
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 normally |
|
28 ## distributed with mean of zero and variance 1. |
|
29 ## |
|
30 ## Note: sometimes the actual density may be a bit smaller than @var{d}. |
|
31 ## This is unlikely to happen for large really sparse matrices. |
|
32 ## |
|
33 ## If called with a single matrix argument, a random sparse matrix is |
|
34 ## generated wherever the matrix @var{S} is non-zero. |
5642
|
35 ## @seealso{sprand} |
5164
|
36 ## @end deftypefn |
|
37 |
|
38 ## Author: Paul Kienzle <pkienzle@users.sf.net> |
|
39 |
6498
|
40 function S = sprandn (m, n, d) |
|
41 if (nargin == 1) |
|
42 [i, j, v, nr, nc] = spfind (m); |
|
43 S = sparse (i, j, randn (size (v)), nr, nc); |
|
44 elseif (nargin == 3) |
5164
|
45 mn = m*n; |
6498
|
46 k = round (d*mn); |
|
47 idx = unique (fix (rand (min (k*1.01, k+10), 1) * mn)) + 1; |
|
48 ## idx contains random numbers in [1,mn] |
|
49 ## generate 1% or 10 more random values than necessary in order to |
|
50 ## reduce the probability that there are less than k distinct |
|
51 ## values; maybe a better strategy could be used but I don't think |
|
52 ## it's worth the price. |
|
53 |
|
54 ## actual number of entries in S |
|
55 k = min (length (idx), k); |
|
56 j = floor ((idx(1:k)-1)/m); |
5164
|
57 i = idx(1:k) - j*m; |
6498
|
58 if (isempty (i)) |
|
59 S = sparse (m, n); |
5164
|
60 else |
6498
|
61 S = sparse (i, j+1, randn (k, 1), m, n); |
5164
|
62 endif |
|
63 else |
6046
|
64 print_usage (); |
5164
|
65 endif |
|
66 endfunction |