5164
|
1 ## Copyright (C) 2004 Paul Kienzle |
|
2 ## |
|
3 ## This program is free software and is in the public domain |
|
4 |
|
5 ## -*- texinfo -*- |
|
6 ## @deftypefn {Function File} {} sprand (@var{m}, @var{n}, @var{d}) |
|
7 ## @deftypefnx {Function File} {} sprand (@var{s}) |
|
8 ## Generate a random sparse matrix. The size of the matrix will be |
|
9 ## @var{m} by @var{n}, with a density of values given by @var{d}. |
5610
|
10 ## @var{d} should be between 0 and 1. Values will be uniformly |
|
11 ## distributed between 0 and 1. |
5164
|
12 ## |
|
13 ## Note: sometimes the actual density may be a bit smaller than @var{d}. |
|
14 ## This is unlikely to happen for large really sparse matrices. |
|
15 ## |
|
16 ## If called with a single matrix argument, a random sparse matrix is |
|
17 ## generated wherever the matrix @var{S} is non-zero. |
5642
|
18 ## @seealso{sprandn} |
5164
|
19 ## @end deftypefn |
|
20 |
|
21 ## This program is public domain |
|
22 ## Author: Paul Kienzle <pkienzle@users.sf.net> |
|
23 ## |
|
24 ## Changelog: |
|
25 ## |
|
26 ## Piotr Krzyzanowski <przykry2004@users.sf.net> |
|
27 ## 2004-09-27 use Paul's hint to allow larger random matrices |
|
28 ## at the price of sometimes lower density than desired |
|
29 ## David Bateman |
|
30 ## 2004-10-20 Texinfo help and copyright message |
|
31 |
|
32 function S = sprand (m, n, d) |
6498
|
33 if (nargin == 1) |
|
34 [i, j, v, nr, nc] = spfind (m); |
|
35 S = sparse (i, j, rand (size (v)), nr, nc); |
|
36 elseif (nargin == 3) |
5164
|
37 mn = n*m; |
6498
|
38 ## how many entries in S would be satisfactory? |
|
39 k = round (d*mn); |
|
40 idx = unique (fix (rand (min (k*1.01, k+10), 1) * mn)) + 1; |
|
41 ## idx contains random numbers in [1,mn] |
|
42 ## generate 1% or 10 more random values than necessary in order to |
|
43 ## reduce the probability that there are less than k distinct |
|
44 ## values; maybe a better strategy could be used but I don't think |
|
45 ## it's worth the price |
|
46 |
|
47 ## actual number of entries in S |
|
48 k = min (length (idx), k); |
|
49 j = floor ((idx(1:k)-1)/m); |
5164
|
50 i = idx(1:k) - j*m; |
6498
|
51 if (isempty (i)) |
|
52 S = sparse (m, n); |
5164
|
53 else |
6498
|
54 S = sparse (i, j+1, rand (k, 1), m, n); |
5164
|
55 endif |
|
56 else |
6046
|
57 print_usage (); |
5164
|
58 endif |
|
59 endfunction |